package com.mall.interceptor;

/**
 * @description:
 * @author: liang
 * @time: 2024-01-17 10:50
 */
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.mall.entity.User;
import com.mall.exception.ServiceException;
import com.mall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，验证权限，是否登录过期，检擦请求头中是否含有token
 */
public class JwtInterceptor implements HandlerInterceptor {


    @Autowired
    private Environment env;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //options直接放行
        if ("OPTIONS".equals(request.getMethod().toUpperCase())){
            return true;
        }
        String token = request.getHeader("Authorization");

        // 执行认证，没有携带token
        if (StrUtil.isBlank(token)) {
            response.setStatus(403);
            throw new ServiceException("403", "请登录");
        }
        // 获取 token 中的 user id
        String userId;
        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(env.getProperty("jwt.sign.property"))).build();
        try {
            jwtVerifier.verify(token); // 验证token
            userId = JWT.decode(token).getAudience().get(0);
            request.setAttribute("userId",userId);

        } catch (JWTVerificationException e) {
            response.setStatus(403);
            throw new ServiceException("403", "请登录");
        }

        return true;
    }
}